package com.quick.gateway.config;
import com.quick.common.Constent.Quick;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.util.List;

import static com.quick.common.util.TokenUtil.getInfo;
import static com.quick.common.util.TokenUtil.verify;

/**
 * 网关Token验证过滤器
 * 用于拦截请求并验证Token有效性
 */
@Component
public class TokenVerifyFilter implements GlobalFilter, Ordered {

    // 白名单路径，不需要验证Token
    private static final List<String> WHITE_LIST = List.of(
            "/user/login",
            "/user/register",
            "/driver/login",
            "/driver/register"
    );

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, org.springframework.cloud.gateway.filter.GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        // 获取请求路径
        String path = request.getPath().toString();

        // 检查是否在白名单中，如果是则直接放行
        if (isWhiteList(path)) {
            return chain.filter(exchange);
        }

        // 从请求头中获取Token
        String token = request.getHeaders().getFirst(Quick.TOKEN_AUTHORIZATION);

        System.out.println("token:"+token);
        // 检查Token是否存在
        if (token == null || token.isEmpty()) {
            return setUnauthorizedResponse(response, "Token不存在");
        }

        // 处理Bearer前缀
        if (token.startsWith("Bearer ")) {
            token = token.substring(7);
        }

        // 验证Token有效性
        if (!verify(token)) {
            return setUnauthorizedResponse(response, "令牌已失效或者已过期");
        }

        // Token验证通过，解析用户信息并添加到请求头中（可选）
        String userId = getInfo(token, Quick.TOKEN_KEY_ID);
        if (userId != null) {
            ServerHttpRequest modifiedRequest = request.mutate()
                    .header("X-User-Id", userId)
                    .build();
            exchange = exchange.mutate().request(modifiedRequest).build();
        }

        // 放行请求
        return chain.filter(exchange);
    }

    /**
     * 检查路径是否在白名单中
     */
    private boolean isWhiteList(String path) {
        return WHITE_LIST.stream().anyMatch(whitePath ->
                path.startsWith(whitePath.replace("**", "")) ||
                        (whitePath.endsWith("**") && path.startsWith(whitePath.substring(0, whitePath.length() - 2)))
        );
    }


    /**
     * 设置未授权响应
     */
    private Mono<Void> setUnauthorizedResponse(ServerHttpResponse response, String message) {
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().add("Content-Type", "application/json");
        String body = "{\"code\":" + HttpStatus.UNAUTHORIZED.value() + ",\"message\":\"" + message + "\"}";
        return response.writeWith(Mono.just(response.bufferFactory().wrap(body.getBytes())));
    }

    /**
     * 过滤器优先级，数值越小优先级越高
     */
    @Override
    public int getOrder() {
        return -100; // 确保在路由过滤器之前执行
    }
}
